import { defineStore } from 'pinia'
import { varietyAPI } from '../api'
import { mockMovies } from '../utils/mockData'
import type { Movie } from '../utils/http'

export const useVarietyStore = defineStore('variety', {
  state: () => ({
    varietyShows: [] as any[],
    loading: false,
    error: '',
    currentPage: 0,
    pageSize: 20,
    total: 0
  }),

  getters: {
    hasMore: (state) => {
      return state.varietyShows.length < state.total
    },
    isEmpty: (state) => {
      return !state.loading && state.varietyShows.length === 0
    }
  },

  actions: {
    async fetchHotVarietyShows() {
      this.loading = true
      this.error = ''
      try {
        const response = await varietyAPI.getHotVarietyShows({
          category: 'show',
          type: 'show',
          limit: this.pageSize,
          start: 0
        })
        const data = response.list || response
        
        if (data && Array.isArray(data)) {
          this.varietyShows = data
          this.total = data.length
        } else if (data && data.data && Array.isArray(data.data)) {
          this.varietyShows = data.data
          this.total = data.total || data.data.length
        } else {
          // 使用模拟数据作为后备
          this.varietyShows = mockMovies.slice(0, 10)
          this.total = this.varietyShows.length
        }
        
        this.currentPage = 1
      } catch (error) {
        console.error('获取综艺数据失败:', error)
        this.error = '获取综艺数据失败，请稍后重试'
        // 使用模拟数据作为后备
        this.varietyShows = mockMovies.slice(0, 10)
        this.total = this.varietyShows.length
      } finally {
        this.loading = false
      }
    },

    async loadMore() {
      if (this.loading || !this.hasMore) return
    
      this.loading = true
      const start = this.currentPage * this.pageSize
      try {
        const response = await varietyAPI.getHotVarietyShows({
          category: 'show',
          type: 'show',
          limit: this.pageSize,
          start: start
        })
        const data = response.data || response
        
        if (data && Array.isArray(data)) {
          this.varietyShows.push(...data)
          this.currentPage += 1
        } else if (data && data.data && Array.isArray(data.data)) {
          this.varietyShows.push(...data.data)
          this.currentPage += 1
        } else {
          // 使用模拟数据作为后备
          const moreData = mockMovies.slice(start, start + this.pageSize)
          this.varietyShows.push(...moreData)
          this.currentPage += 1
        }
      } catch (error) {
        console.warn('API调用失败，使用模拟数据:', error)
        // 使用模拟数据作为后备
        const mockData = mockMovies.slice(start, start + this.pageSize)
        this.varietyShows.push(...mockData)
        this.currentPage += 1
      } finally {
        this.loading = false
      }
    },

    reset() {
      this.varietyShows = []
      this.loading = false
      this.error = ''
      this.currentPage = 0
      this.total = 0
    }
  }
})